'use strict';
define('controller', ['app'], function (app) {

    app.controller("IndexIndexController", ['$scope', '$rootScope', '$state', 'UserService', function ($scope, $rootScope, $state, userService) {
        // do nothing
        setInterval(function () {
            if (userService.user.logined) {
                $.post($.urlBuild('index', 'chew'), {}, function (data) {
                    // avoid loginout
                });
            }
        }, 60 * 1000);
    }]);

    app.controller('IndexHeaderController', ['$scope', '$state', '$http', 'UserService', function ($scope, $state, $http, userService) {
        $scope.data = {
            username: userService.user.username
        };
        $scope.$state = $state;
        $scope.logout = function () {
            $http.get($.urlBuild('user', 'logout'), {cache: false}).success(function (data) {
                userService.user.logined = false;
                userService.user.username = '';
                window.location.href = TPX.PATH_ROOT + '/';
            });
        };
    }]);

    app.controller('UserIndexController', ['$scope', '$state', '$http', '$stateParams', 'UserService', function ($scope, $state, $http, $stateParams, userService) {
        $scope.data = {
            username: userService.user.username
        };
        if ('user' == $state.current.name) {
            $state.go('user.profile');
        }
        $scope.$state = $state;
    }]);

    app.controller('UserRegisterController', ['$scope', '$state', 'UserService', function ($scope, $state, userService) {
        $scope.data = {
            username: '',
            password: '',
            'password-repeat': ''
        };
        $scope.submit = function (valid) {
            if (!valid) {
                $.dialog.tips('注册信息有误', 1.5, 'error.gif');
                return;
            }
            $.post($.urlBuild('user', 'register'), $scope.data, function (data) {
                if (data.status == 1) {
                    $.dialog.alert('注册成功', function () {
                        $scope.$apply(function () {
                            $state.go('login');
                        });
                    });
                } else {
                    $.dialog.tips(data.info, 1.5, 'error.gif');
                }
            });
        };
    }]);
    app.controller('UserLoginController', ['$scope', '$state', 'UserService', function ($scope, $state, userService) {
        $scope.data = {
            username: '',
            password: ''
        };
        $scope.submit = function (valid) {
            if (!valid) {
                $.dialog.tips('登录信息有误', 1.5, 'error.gif');
                return;
            }
            $.post($.urlBuild('user', 'login'), $scope.data, function (data) {
                if (data.status == 1) {
                    window.location.href = TPX.PATH_ROOT + '/';
                } else {
                    $.dialog.tips(data.info, 1.5, 'error.gif');
                }
            });
        };
    }]);
    app.controller('UserProfileController', ['$scope', '$state', '$http', 'UserService', 'ResponseChecker', 'UI',
        function ($scope, $state, $http, userService, responseChecker, ui) {
            $scope.userService = userService;
            $scope.$watch('userService.data', function () {

            });
            $scope.submit = function (valid) {
                alert(1);
                if (!valid) {
                    ui.error.show('信息填写不完整');
                    return;
                }
                $scope.userService.data.doc_header_image = $('#doc_header_image').val();
                userService.submitProfile();
            };

            $scope.$watch('$viewContentLoaded', function () {
                require(["upload_button"], function () {
                    $("#imagefile_doc_header_image").UploadButton({
                        value_holder: "#doc_header_image",
                        preview_holder: "#doc_header_image-preview",
                        width: 24,
                        height: 24,
                        postURL: $.urlBuild('system', 'uploadhandle', {action: 'uploadbutton', type: 'image'}),
                        background: "http://" + document.location.hostname + TPX.PATH_ROOT + "/asserts/upload_button/upload_24x24.png",
                        acceptExt: ".jpg,.png",
                        showLoading: true,
                        showAlert: false
                    });
                });
            });

        }]);
    app.controller('UserChangepwdController', ['$scope', '$state', '$http', 'UserService', function ($scope, $state, $http, userService) {
        $scope.data = {
            'password': '',
            'password-new': '',
            'password-repeat': ''
        };
        $scope.submit = function (valid) {
            if (!valid) {
                $.dialog.tips('数据信息有误', 1.5, 'error.gif');
                return;
            }
            $.post($.urlBuild('user', 'changepwd'), $scope.data, function (data) {
                if (data.status == 1) {
                    $scope.$apply(function () {
                        $.dialog.tips('修改成功', 1.5, 'success.gif');
                        $http.get($.urlBuild('user', 'logout'), {cache: false}).success(function (data) {
                            userService.user.logined = false;
                            userService.user.username = '';
                            $state.go('login');
                        });
                    });
                } else {
                    $.dialog.tips(data.info, 1.5, 'error.gif');
                }
            });
        };
    }]);


    app.controller('DocIndexController', ['$scope', '$state', 'UserService', '$stateParams', 'DocService',
        function ($scope, $state, userService, $stateParams, docService) {

            docService.one.id = 0;
            docService.one.out_id = '';
            docService.one.cat_id = 0;
            docService.one.title = '';
            docService.one.content = '';
            docService.one.wp_id = 0;


        }]);


    // 文档分类的所有操作
    app.controller('DocCatController', ['$scope', '$state', '$http', 'UserService', 'DocCatService', 'DocService', 'ResponseChecker',
        function ($scope, $state, $http, userService, docCatService, docService, responseChecker) {

            $scope.docCatService = docCatService;
            $scope.docService = docService;

            docService.catScope = $scope;

            $scope.data = {
                id: 0,
                title: ''
            };

            $scope.edit = function (id, $event) {
                if ($event) {
                    $event.stopPropagation();
                }
                id = id || 0;
                var cat = docCatService.load(id);
                if (!id || null === cat) {
                    $scope.data.title = '';
                    $scope.data.id = 0;
                } else {
                    $scope.data.title = cat.title;
                    $scope.data.id = cat.id;
                }
                $('#cat-edit').modal();
            };

            $scope.delete = function () {
                docCatService.delete($scope.data, function (data) {
                    if (data.status == 1 && data.info == 'ok') {
                        docCatService.reload(function () {
                            $scope.$apply();
                        });
                        $('#cat-edit').modal('hide');
                    } else {
                        responseChecker.callback(data);
                    }
                });
            };

            $scope.submit = function () {
                if ($scope.data.id > 0) {
                    docCatService.edit($scope.data, function (data) {
                        if (data.status == 1 && data.info == 'ok') {
                            docCatService.reload(function () {
                                $scope.$apply();
                            });
                            $('#cat-edit').modal('hide');
                        } else {
                            responseChecker.callback(data);
                        }
                    });
                } else {
                    docCatService.add($scope.data, function (data) {
                        if (data.status == 1 && data.info == 'ok') {
                            docCatService.reload(function () {
                                $scope.$apply();
                            });
                            $('#cat-edit').modal('hide');
                        } else {
                            responseChecker.callback(data);
                        }
                    });
                }
            };

            $scope.load = function (id) {
                if (!docService.one.id) {
                    docService.one.cat_id = id;
                }
                docService.fetch(id, 1);
            };

            var keywordSearchTriggerTimer = null;
            $scope.$watch('docService.search.keywords', function () {
                if (null != keywordSearchTriggerTimer) {
                    clearTimeout(keywordSearchTriggerTimer);
                }
                keywordSearchTriggerTimer = setTimeout(function () {
                    docService.fetch(undefined, 1);
                }, 500);
            });

        }]);

    app.controller('DocListController', ['$scope', '$state', 'DocService', 'DocDraftService', 'DocCatService',
        function ($scope, $state, docService, docDraftService, docCatService) {

            $scope.docService = docService;

            docService.listScope = $scope;

            $scope.$watch('$viewContentLoaded', function () {
                var $list = $('#b-doc .c-list .list');
                var loading = function () {
                    if ($('.list-loading', $list).isOnScreen()) {
                        docService.fetch(docService.fetch_cat_id);
                    }
                };
                $list.scroll(function () {
                    loading();
                });
                loading();
            });

            $scope.$watch('docService.data', function () {
                var $list = $('#b-doc .c-list .list');
                var load = function () {
                    if (!docService.fetch_end && $('.list-loading', $list).isOnScreen()) {
                        docService.fetch(docService.fetch_cat_id);
                        setTimeout(function () {
                            load();
                        }, 50);
                    }
                };
                load();
            });

            $.fn.isOnScreen = function () {
                var win = $(window);
                var viewport = {
                    top: win.scrollTop(),
                    left: win.scrollLeft()
                };
                viewport.right = viewport.left + win.width();
                viewport.bottom = viewport.top + win.height();
                var bounds = this.offset();
                bounds.right = bounds.left + this.outerWidth();
                bounds.bottom = bounds.top + this.outerHeight();
                return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
            };

            $scope.edit = function (id) {
                var edit = function () {
                    $state.go('doc.edit', {id: id});
                    docService.load(id, function () {
                        docDraftService.checkAndNotice();
                        setTimeout(function () {
                            $scope.$apply();
                        }, 0);
                    });
                };
                var content = docService.getMarkdown();
                if (content != docService.one.content) {
                    $.dialog.confirm('当前文档未保存，继续操作将丢失修改的数据', function () {
                        docDraftService.clear();
                        edit();
                    });
                } else {
                    edit();
                }
            };

            $scope.delete = function (id) {
                $.dialog.confirm('删除之后将不可恢复，确认？', function () {
                    docService.delete(id, function () {
                        docCatService.reload(function () {
                            if (docService.catScope) {
                                docService.catScope.$apply();
                            }
                        });
                    });
                });
            };

        }]);

    app.controller('DocBodyController', ['$scope', '$state', 'UserService', 'DocCatService', 'DocService',
        'DocDraftService', 'ResponseChecker', 'UI', 'SystemService',
        function ($scope, $state, userService, docCatService, docService, docDraftService, responseChecker, ui, systemService) {
            $scope.docCatService = docCatService;
            $scope.docService = docService;
            docService.bodyScope = $scope;

            if ('id' in $state.params) {
                docService.load($state.params.id, function () {
                    docDraftService.checkAndNotice();
                    setTimeout(function () {
                        $scope.$apply();
                    }, 0);
                });
            }

            $scope.fullscreen = function () {
                var o = $('#iframe_editor');
                if (o.attr('data-fullscreen') == 'true') {
                    o
                        .attr('data-fullscreen', 'false')
                        .css({
                            position: '',
                            left: 0,
                            top: 0,
                            width: '100%',
                            height: $(window).height() - 40 - 41 + 'px'
                        });
                    $('.btn-fullscreen img').attr('src', TPX.PATH_ASSERTS + '/res/img/icon_fullscreen.png');
                } else {
                    o
                        .attr('data-fullscreen', 'true')
                        .css({
                            position: 'absolute',
                            left: 0,
                            top: 0,
                            width: $(window).width() + 'px',
                            height: $(window).height() + 'px'
                        });
                    $('.btn-fullscreen img').attr('src', TPX.PATH_ASSERTS + '/res/img/icon_fullscreen_exit.png');
                }
                docService.fullscreenMarkdown();
            };

            window.onbeforeunload = function () {
                var content = docService.getMarkdown();
                if (content != docService.one.content) {
                    return '刷新页面将丢失未保存的数据';
                }
            };


            $scope.submit = function () {
                docDraftService.clear();
                docService.submit(function () {
                    docCatService.reload(function () {
                        if (docService.catScope) {
                            docService.catScope.$apply();
                        }
                    });
                });
            };

            $scope.history = function () {
                docService.fetch_history();
            };

            $scope.historyRestore = function (history_id) {
                docService.restore_history(history_id);
            };

            $scope.historyShow = function ($event) {
                var o = $($event.target);
                if (o.css('max-height') == '150px') {
                    o.css({
                        maxHeight: '100%'
                    });
                } else {
                    o.css({
                        maxHeight: '150px'
                    });
                }
            };


            if (systemService.config.wordpress_syncer_enable) {

                $scope.wordpressPublish = function () {
                    $('#wordpress-publish').modal();
                };

                $scope.wordpressPublishSubmit = function () {
                    var categorys = [];
                    $('input[name=wordpress_categorys]:checked').each(function (i, o) {
                        categorys.push($(o).val());
                    })
                    docService.wordpress_submit(categorys, function () {
                        $('input[name=wordpress_categorys]').prop('checked', false);
                        $('#wordpress-publish').modal('hide');
                        $scope.$apply();
                    });
                };

                $scope.wordpressSync = function ($event) {
                    var url_tpl = $($event.target).closest('a').attr('data-tpl');
                    docService.wordpress_sync(function () {
                        if (url_tpl) {
                            url_tpl = url_tpl.replace(/\{id\}/g, docService.one.wp_id);
                            $.dialog.alert('同步成功 <a href="' + url_tpl + '" target="_blank">点击查看</a>');
                        } else {
                            ui.success.show('同步成功');
                        }
                    });
                };

                $scope.wordpressUnlink = function () {
                    $.dialog.confirm('断开后将不能再次关联Wordpress中此篇文章，确定要这样做吗？', function () {
                        docService.wordpress_unlink(function () {
                            $scope.$apply();
                        });
                    });
                };


                $scope.data_wordpress_categorys = [];

                // 获取最新的分类信息
                $.post($.urlBuild('doc', 'fetch_wordpress_category'), {}, function (data) {
                    if (data.status == 1) {
                        $scope.data_wordpress_categorys = data.data;
                    } else {
                        responseChecker.callback(data);
                    }
                });

            }

        }]);

});